<?php

// +----------------------------------------------------------------------
// | OneChat
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.tealun.com
// +----------------------------------------------------------------------
// | Author: Tealun Du <tealun@tealun.com> <http://www.tealun.com>
// +----------------------------------------------------------------------

namespace Admin\Controller;

use Wechat\Api\ClientApi;
/**
 * 微信客户管理控制器

 */
class WechatClientController extends WechatController {

    protected $Client = null;

    function _initialize(){
        $this->Client = new ClientApi();
        parent::_initialize();
    }

    /**
     *客户列表
     *TODO 将客户列表分为两个选项卡显示，一个为正在关注列表，一个为已取消关注列表
     */
    public function index() {

        $map = array();

        if ( isset( $_GET['subscribe'] ) ) {
            $map['subscribe'] = array('eq',$_GET['subscribe']);
        }else{
            $map['subscribe'] = array('eq',1);
        }

        if ( isset( $_GET['tag'] ) ) {
            $openid = $this->getTagOpenid($_GET['tag']);
            if($openid){
                $map['openid'] = array('in',$openid);
            }
        }

        if ( isset( $_GET['time-start'] ) ) {
            $map['subscribe_time'][] = array( 'egt' , strtotime(I('time-start')) );
        }
        if ( isset( $_GET['time-end'] ) ) {
            $map['subscribe_time'][] = array( 'elt' , 24 * 60 * 60+strtotime(I('time-end')) );
        }

        $this->getLists('Tchat_client',$map,'subscribe_time desc,id','id,openid,headimgurl,nickname,subscribe,subscribe_time,uid,remark,sex,tagid_list,city,country,province');

        $this->jsonAllTags();
        $this->meta_title = '正在关注客户列表';
        $this->display(); // 输出模板
    }

    /**
     * 粉丝详情
     * @param $id
     */
    public function detail($id){
        $info = $this->Client->getInfo($id,'id,headimgurl,nickname,subscribe,subscribe_time,uid,remark,sex,tagid_list,city,country,province,language');
        if(!$info){
            $this->error('没有找到该用户信息，请核对后重试');
        }
        $info['tags']= $this->tagidToTags($info['tagid_list']);
        unset($info['tagid_list']);
        $this->jsonAllTags();
        $this->assign('info',$info);
        $this->meta_title = '客户详情查看';
        $this->display();
    }

    /**
     * 标签列表
     */
    public function tags() {
        //新增标签操作
        if(IS_POST || IS_AJAX){
            $data = I('post.');
            switch ($data['act']){

                case 'create':
                    $re = $this->Client->createTag($data['name']);
                    if($re['errcode']){
                        $this->error('添加标签失败,失败原因：'.$re['errmsg']);
                    }else{
                        $this->success('添加标签成功',U());
                    }
                    break;
                case 'refreshTag':
                    get_wechat_tags(true);
                    $this->success('刷新成功',U());
                    break;
                default:
                    $this->error('未指定操作类型');
            }
        }

        $tags = get_wechat_tags();

        $this->assign('_Tags',$tags);
        $this->meta_title = '用户标签管理';
        $this->display();
    }

    /**
     * 设置客户信息
     * @return int
     */
    public function setClientInfo(){
        if(IS_POST){
            $column = I('post.name');
            $id = I('post.pk');
            $value = I('post.value');
            $re = $this->Client->$column($id,$value);
            if($re == true){
                $this->success('设置成功');
            }else{
                $this->error($re);
            }
        }

}

    /**
     *导入微信粉丝
     */
    public function importClient(){
        if(IS_POST){
            if(I('post.all') == 1){
                $nextOpenid = '';
            }else{
                $nextOpenid = false;
            }

            $this->startImport($nextOpenid);

        }else{
            $this->meta_title = '导入微信粉丝';
            $this->display();
        }

    }

    /**
     * 获取后台更新进度
     */
    public function getProgress(){
        if(IS_POST){
            $name = I('post.name');
            if(I('post.clear')){
                S('progress'.$name,NULL);
            }else{
                $data = S('progress'.$name)?S('progress'.$name):false;
                $this->ajaxReturn($data);
            }
        }else{
            $this->display();
        }
    }

    /**
     * 开始导入粉丝
     * @param $nextOpenid
     */
    private function startImport($nextOpenid){
        $this->saveProgress('importClient',5,'开始导入：');
        sleep(2);

        $data = $this->Client->importClient($nextOpenid);
        if($data){
            $this->saveProgress('importClient',5,'粉丝总数：'.$data['total'].'本次获取粉丝数：'.$data['count']);
            
            $this->saveProgress('importClient',6,'开始导入粉丝数据');
            

            $nextOpenid=$data['next_openid'];
            S('importNextOpenid',$nextOpenid);

            $openids = $data['data']['openid'];
            var_dump($openids);
            $update = 0;
            $add = 0;

            if($data['count'] >0){
                for($i=0;$i<$data['count'];$i++){
                    $info = get_client_info($openids[$i]);

                    if($info['errcode']){
                        $this->saveProgress('importClient',$i/$data['count']*90+9,'获取openid'.$openids[$i].'信息时出错'.$info['errmsg']);
                        S('importNextOpenid',$openids[$i]);
                        exit;
                    }

                    $id = $this->Client->getClientId($openids[$i]);
                    if($id){
                        $info['id'] = $id;
                        $update ++;
                    }else{
                        $add ++;
                    }
                    $re = $this->Client->update($info);
                    if(!is_numeric($re)){
                        $this->saveProgress('importClient',$i/$data['count']*90+9,'导入粉丝'.$info['nickname'].'时出错');
                        S('importNextOpenid',$openids[$i]);
                        exit;
                    }
                    $this->saveProgress('importClient',$i/$data['count']*90+9,'导入粉丝['.$info['nickname'].']成功');
                }
            }
            $this->saveProgress('importClient',100,'粉丝导入成功，本次更新粉丝['.$update.']人，新增粉丝['.$add.']人');
        }

        
    }

    /**
     * 获取标签下的openid
     * @param $tagid
     * @param string $nextOpenid
     * @return bool
     * fixme 如果一次拉取不完 需要调整获取方法
     */
    private function getTagOpenid($tagid,$nextOpenid = ''){

        $re = get_tag_openid($tagid,$nextOpenid);
        if($re['errcode']){
            $this->error($re['errmsg']);
            return false;
        }else{
            $data = $re['data'];
        }
        return $data['openid'];
    }

    /**
     * 获取客户数据
     *
     * @param array $map
     */
    private function getLists($model,$map,$order='',$filed=true) {
        $list = $this->lists($model , $map,$order,$filed);
        col_to_string($list);
        foreach($list as $key => $value){
            if(!empty($value['tagid_list'])){
                $tags = $this->tagidToTags($value['tagid_list']);
                $list[$key]['tags']=$tags;
            }
        }

        $this->assign('_list' , $list);
    }

    /**
     * 实时显示提示信息
     * @param  string $msg 提示信息
     * @param  string $class 输出样式（success:成功，error:失败）
     * @author huajie <banhuajie@163.com>
     */
    private function saveProgress($name,$progress,$msg){
        $arr = array(
            'progress'=>$progress,
            'msg'=>$msg
        );
        S('progress'.$name,$arr);
    }

    /**
     * 将标签id转换成name
     * @param $tagid_list
     *
     * @return mixed
     */
    private function tagidToTags($tagid_list){
        $tagids = explode(',',$tagid_list);
        foreach($tagids as $k => $v){
            $tags[$v] = get_tag_name($v);
        }
        $tags = arr2str($tags);
        return $tags;
    }

    private function jsonAllTags(){
        $allTags = get_wechat_tags();
        foreach($allTags as $k=>$v){
            $allTags[$k]['text'] = $v['name'];
            unset($allTags[$k]['name'],$allTags[$k]['count']);
        }
        $allTags = JSON($allTags);

        $this->assign('allTags',$allTags);
    }

}